package com.lemon.smartsafety.ui.activity.fire.item.inspection;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatRadioButton;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableRow;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.RefreshViewData;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.common.CommonVoEx;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.FireBuildGroupItem;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * 现场检查增加建筑
 */
public class FireInspectionAddBuildActivity extends PhotoSelectBaseActivity {
    //private LoggerHelper loggerHelper = new LoggerHelper(SafeDataCollectionBuildingPropActivity.class);

    @Bind(R.id.metBuildTitle)
    MaterialEditText metBuildTitle;
    @Bind(R.id.metPlaceType)
    MaterialEditText metPlaceType;
    @Bind(R.id.rowPlaceType)
    TableRow rowPlaceType;
    @Bind(R.id.metBuildingGroup)
    MaterialEditText metBuildingGroup;
    @Bind(R.id.rowGroupSetting)
    TableRow rowGroupSetting;
    @Bind(R.id.metRemark)
    MaterialEditText metRemark;
    @Bind(R.id.radioAll)
    AppCompatRadioButton radioAll;
    @Bind(R.id.radioPart)
    AppCompatRadioButton radioPart;

    @Bind(R.id.metFloorUp)
    MaterialEditText metFloorUp;
    @Bind(R.id.metFloorDown)
    MaterialEditText metFloorDown;
    @Bind(R.id.iv_photo)
    ImageView ivPhoto;
    @Bind(R.id.rowPhotoPick)
    TableRow rowPhotoPick;
    @Bind(R.id.metEast)
    MaterialEditText metEast;
    @Bind(R.id.metSouth)
    MaterialEditText metSouth;
    @Bind(R.id.metWest)
    MaterialEditText metWest;
    @Bind(R.id.metNorth)
    MaterialEditText metNorth;
    @Bind(R.id.btn_submit)
    Button btnSubmit;


    /**
     * 建筑分类
     */
    private CommonVoEx fireBuildPlaceItem = null;
    private String txtBuildingTitle = "";
    private String txtFloor = "";
    private String txtUnder = "";
    private String txtEast = "";
    private String txtSouth = "";
    private String txtWest = "";
    private String txtNorth = "";


    private PhotoInfo mPhotoInfo;

    private MaterialDialog.Builder mMaterialDialog;

    private boolean isEdit = false;
    private FireBuildGroupItem fireBuildGroupItem;

    private SuperviseCompanyResult.ResultEntity resultEntity;


    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.build_prop_title);
    }


    /****************************************************************************************************************
     * 保护现场
     ****************************************************************************************************************/
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(BundleKey.COMPANY_FIRE_INFO, resultEntity);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) savedInstanceState.getSerializable(BundleKey.FIRE_COMPANY_BASE_INFO);
        }
    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fire_inspection_add_build;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ivPhoto.setTag("0");

        if (null == resultEntity) {
            mHUDUtil.showErrorTip(R.string.params_error);
            AppManager.getAppManager().finishActivity(FireInspectionAddBuildActivity.this);
            return;
        }



    }

    private void initEditView(CompanyBuildingVo vo) {
        metBuildTitle.setText(StringUtils.nullValue(vo.getBuildingTitle()));
        metPlaceType.setText(StringUtils.nullValue(vo.getBuildType().getName()));
        fireBuildPlaceItem = vo.getBuildType();


        metBuildingGroup.setText(StringUtils.nullValue(vo.getGroupName()));
        metBuildingGroup.setTag(StringUtils.nullValue(vo.getGroupIds()));

        metRemark.setText(StringUtils.nullValue(vo.getRemark()));
        if (StringUtils.nullValue(vo.getOccupy()).equals("0")) {
            radioAll.setChecked(false);
            radioPart.setChecked(true);
        } else {
            radioAll.setChecked(true);
            radioPart.setChecked(false);
        }
        metFloorUp.setText(StringUtils.nullValue(vo.getFloor()));
        metFloorDown.setText(StringUtils.nullValue(vo.getUnder()));
        metEast.setText(StringUtils.nullValue(vo.getEast()));
        metSouth.setText(StringUtils.nullValue(vo.getSouth()));
        metWest.setText(StringUtils.nullValue(vo.getWest()));
        metNorth.setText(StringUtils.nullValue(vo.getNorth()));

        String photoUrl = StringUtils.nullValue(vo.getImageUrl());
        if (photoUrl.length() != 0) {
            photoUrl = HttpUtils.formatFilesUrl(photoUrl);
            mPhotoInfo = new PhotoInfo();
            mPhotoInfo.setPhotoId(Integer.MAX_VALUE);
            mPhotoInfo.setPhotoPath(photoUrl);
            ivPhoto.setTag(photoUrl);

            GlideImageLoader.loadImage(this, photoUrl, ivPhoto);
        } else {
            ivPhoto.setTag("0");
        }


    }


    @Subscribe
    public void onEventMainThread(RefreshViewData event) {
        //建筑场所
        if (FireInspectionGroupListActivity.class.getName().equals(event.getTAG())) {
            fireBuildGroupItem = (FireBuildGroupItem) event.getData();
            if (!CommonUtil.objIsEmpty(fireBuildGroupItem)) {
                metBuildingGroup.setText(StringUtils.nullValue(fireBuildGroupItem.getGroupName()));
                metBuildingGroup.setTag(StringUtils.nullValue(fireBuildGroupItem.getGroupId()));
            }
        } else if (FireInspectionPlaceListActivity.class.getName().equals(event.getTAG())) {
            fireBuildPlaceItem = (CommonVoEx) event.getData();
            if (!CommonUtil.objIsEmpty(fireBuildPlaceItem)) {
                metPlaceType.setText(StringUtils.nullValue(fireBuildPlaceItem.getName()));
            }
        }
    }


/*    @Subscribe
    public void onEventMainThread(BuildTypeEvent event) {
        if (SafeDataCollectionBuildingTypeListFragment.class.getName().equals(event.getTag())) {
            fireBuildPlaceItem = (CommonVoEx) event.getData();
            if (fireBuildPlaceItem != null) {
                metPlaceType.setText(StringUtils.nullValue(fireBuildPlaceItem.getName()));
            }
        }
    }*/

    @OnClick(R.id.rowPlaceType)
    public void rowPlaceTypeClick() {
        showBuildingTypeList();
    }

    @OnClick(R.id.metPlaceType)
    public void metPlaceTypeClick() {
        showBuildingTypeList();
    }

    private void showBuildingTypeList() {
        if (fireBuildPlaceItem != null) {
            Bundle bundle = new Bundle();
            bundle.putString(BundleKey.OLD_SELECT_VALUE, StringUtils.nullValue(fireBuildPlaceItem.getName()));
            //UIHelper.showSafeDataCollectionBuildingTypeList(this, bundle);
            UIHelper.showActivity(this, bundle, FireInspectionPlaceListActivity.class);
        } else {
            //UIHelper.showSafeDataCollectionBuildingTypeList(this, null);
            UIHelper.showActivity(this, null, FireInspectionPlaceListActivity.class);
        }
    }

    @Override
    protected void callFinish() {
        mMaterialDialog = null;
        resultEntity = null;
        IApplication._tempBuildPropActivity = null;
        AppManager.getAppManager().finishActivity(FireInspectionAddBuildActivity.class);
    }


    @OnClick({R.id.iv_photo, R.id.rowPhotoPick})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_photo:
                if ("0".equals(ivPhoto.getTag()) || "".equals(ivPhoto.getTag())) {
                    showSelectPhoto();
                } else {
                    PhotoInfo photoInfo = new PhotoInfo();
                    photoInfo.setPhotoId(Integer.MAX_VALUE);
                    photoInfo.setPhotoPath(StringUtils.nullValue(ivPhoto.getTag().toString()));
                    UIHelper.showPhotoView(FireInspectionAddBuildActivity.this, photoInfo);
                }
                break;
            case R.id.rowPhotoPick:
                showSelectPhoto();
                break;
        }
    }

    //添加分组
    @OnClick({R.id.metBuildingGroup, R.id.rowGroupSetting})
    public void buildGroupingSetting(View view) {
        Bundle bundle = new Bundle();
        if (fireBuildGroupItem != null) {
            bundle.putString(BundleKey.OLD_SELECT_VALUE, fireBuildGroupItem.getGroupName());
        }
        bundle.putString(BundleKey.COMPANY_CODE, StringUtils.nullValue(resultEntity.getCompanyCode()));
        UIHelper.showActivity(this, bundle, FireInspectionGroupListActivity.class);
    }

    /**
     * 显示选择照片的界面
     */
    public void showSelectPhoto() {
        showActionSheet(EvidenceActionSheetType.CAMERA_ALBUM_SINGLE);
    }


    @Override
    protected void onSinglePhotoSuccess(int requestCode, PhotoInfo photoInfo) {
        super.onSinglePhotoSuccess(requestCode, photoInfo);
        this.mPhotoInfo = photoInfo;
        ivPhoto.setTag(StringUtils.nullValue(photoInfo.getPhotoPath()));
        GlideImageLoader.loadImage(this, StringUtils.nullValue(photoInfo.getPhotoPath()), ivPhoto);
    }


    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        /**
         * 请填写建筑名称
         */
        txtBuildingTitle = StringUtils.nullValue(metBuildTitle.getText().toString().trim());
        if (TextUtils.isEmpty(txtBuildingTitle)) {
            metBuildTitle.setError(getString(R.string.build_prop_error_building_title));
            mHUDUtil.showErrorTip(getString(R.string.build_prop_error_building_title));
            return false;
        }


        /**
         * 请选择场所分类
         */
        if (fireBuildPlaceItem == null) {
            metBuildTitle.setError(getString(R.string.build_prop_error_building_type));
            mHUDUtil.showErrorTip(getString(R.string.build_prop_error_building_type));
            return false;
        }


        /**
         * 请填写地上层数
         */
        txtFloor = StringUtils.nullValue(metFloorUp.getText().toString().trim());
        txtFloor = txtFloor.replace("，", ",");
        if (TextUtils.isEmpty(txtFloor)) {
            metFloorUp.setError(getString(R.string.build_prop_error_floor_up_empty));
            mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_up_empty));
            return false;
        }


        /**
         * 请填写地下层数
         */
        txtUnder = StringUtils.nullValue(metFloorDown.getText().toString().trim());
        if (TextUtils.isEmpty(txtUnder)) {
            txtUnder = "0";
            metFloorDown.setText("0");
        }


        boolean chkOccupy = radioAll.isChecked();

        if (chkOccupy) {
            if (!floorNumberCheck2(txtFloor)) {
                metFloorUp.setError(getString(R.string.build_prop_error_floor_up_format));
                mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_up_format));
                return false;
            }
            if (!floorNumberCheck2(txtUnder)) {
                metFloorDown.setError(getString(R.string.build_prop_error_floor_down_format));
                mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_down_format));
                return false;
            }
        } else {
            if (!floorNumberCheck(txtFloor)) {
                metFloorUp.setError(getString(R.string.build_prop_error_floor_format_tip));
                mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_format_tip));
                return false;
            }
            if (!floorNumberCheck(txtUnder)) {
                metFloorDown.setError(getString(R.string.build_prop_error_floor_format_tip));
                mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_format_tip));
                return false;
            }
        }


        txtEast = metEast.getText().toString().trim();
        txtSouth = metSouth.getText().toString().trim();
        txtWest = metWest.getText().toString().trim();
        txtNorth = metNorth.getText().toString().trim();


      /*  if(CommonUtil.strIsEmpty(txtEast)){
            metEast.setError("方位东,没有填写");
            mHUDUtil.showErrorTip("方位东,没有填写");
            return false;
        }

        if(CommonUtil.strIsEmpty(txtSouth)){
            metSouth.setError("方位南,没有填写");
            mHUDUtil.showErrorTip("方位南,没有填写");
            return false;
        }

        if(CommonUtil.strIsEmpty(txtWest)){
            metWest.setError("方位西,没有填写");
            mHUDUtil.showErrorTip("方位西,没有填写");
            return false;
        }

        if(CommonUtil.strIsEmpty(txtNorth)){
            metNorth.setError("方位北,没有填写");
            mHUDUtil.showErrorTip("方位北,没有填写");
            return false;
        }*/


        return true;

    }


    private boolean floorNumberCheck(String s) {
        //Pattern p1 = Pattern.compile("(^\\d+,?(-?\\d+,?)+(\\d+-)?\\d+$)|(^\\d+$)|(^\\d+(-{1})?\\d+$)");
        Pattern p1 = Pattern.compile("(^\\d+([,-]\\d+)*$)|(^\\d+([,-]\\d+)*$)");
        return p1.matcher(s).matches();
    }

    private boolean floorNumberCheck2(String s) {
        Pattern p1 = Pattern.compile("^\\d+$");
        return p1.matcher(s).matches();
    }


    @OnClick(R.id.btn_submit)
    protected void btnSubmitAction() {
        if (!validateForm()) {
            return;
        }


        mMaterialDialog = getConfirmDialog(getString(R.string.is_submit), new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doPostAction();
                }
            }
        });
        mMaterialDialog.show();

    }


    private void doPostAction() {
        final LemonRequestParams params = new LemonRequestParams("company_building", "building_id", "");
        params.put("_txtIdNumeric", "0");

        params.put("handler", "com.lemon.fire_control.CompanyBuildingAction");
        params.put("op", "new_company_building");


        params.put("building_id", "");


        if (fireBuildGroupItem != null) {
            params.put("txtGroupIds", fireBuildGroupItem.getGroupId(), Field.TYPE_STRING);
        }
        params.put("txtBuildingTitle", txtBuildingTitle, Field.TYPE_STRING);
        params.put("selBuildingTypeCode", fireBuildPlaceItem.getExTitle(), Field.TYPE_STRING);
        params.put("txtRemark", metRemark.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtFloor", txtFloor, Field.TYPE_STRING);
        params.put("txtUnder", txtUnder, Field.TYPE_STRING);
        params.put("txtCompanyCode", resultEntity.getCompanyCode(), Field.TYPE_STRING);
        params.put("chkOccupy", radioAll.isChecked() ? "1" : "0", Field.TYPE_INT);
        params.put("txtEast", StringUtils.nullValue(metEast.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtSouth", StringUtils.nullValue(metSouth.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtWest", StringUtils.nullValue(metWest.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtNorth", StringUtils.nullValue(metNorth.getText().toString().trim()), Field.TYPE_STRING);
        params.put("_txtDataSourceProvider", "com.lemon.fire_control.SafeConnProvider");


        params.put("txtCompanyId", resultEntity.getCompanyId());
        params.put("txtCompanyCode", resultEntity.getCompanyCode());
        params.put("_no_html", "1");


        getSinglePhotoUploadItem(this.mPhotoInfo, new SelectEvidenceAdapter.CropCallBack<String>() {
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mHUDUtil.showHUD();
                    }
                });
            }

            @Override
            public void onFinish(String data) {
                if (StringUtils.nullValue(data).length() != 0) {
                    params.put("file_url", data);
                }
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        //SafeDataServices.init().saveBuildingInfoAction(params, isEdit);
                        initCompanySave(params);
                    }
                });
            }
        });
    }


    /**
     * 保存
     */
    public void initCompanySave(LemonRequestParams params) {
     /*   SharedPreferencesServer mSharedPreferencesServer=new SharedPreferencesServer(IApplication.context());
        String serverUrl = mSharedPreferencesServer.getRequestUrl( UrlInfo.BIND_COMPANY_EDIT_ACTION );
        LogUtils.LOGE("serverUrl:"+serverUrl);*/

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.ActionServlet), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            ToastUtils.toastMsg(baseMode.getMsg());
                            //mHUDUtil.showDoneTip(oldBaseMode.getError().getMsg());

                            //通知列表页面刷新
                            EventBus.getDefault().post(new RefreshViewEntity(FireInspectionAddBuildActivity.class.getName()));

                            AppManager.getAppManager().finishActivity(FireInspectionAddBuildActivity.this);
                            callFinish();
                        } else {
                            //oldBaseMode.getError().getMsg();
                            mHUDUtil.showErrorTip(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }


    /**
     * 处理所有的网络请求返回
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent event) {
        if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_SAVE == event.getTag()) {//建筑保存
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                            //通知列表页面刷新
                            EventBus.getDefault().post(new RefreshViewEntity(FireInspectionAddBuildActivity.class.getName()));
                            AppManager.getAppManager().finishActivity(FireInspectionAddBuildActivity.this);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resultEntity = null;
        IApplication._tempBuildPropActivity = null;
        System.gc();

    }
}